package websocet1;

/**
 * @Auther: 杨通通
 * @Date: 2024/10/28 23:42
 * @Description:
 */


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * TextWebSocketFrame  表示一个文本贞
 * 浏览器和服务端以TextWebSocketFrame 格式交互
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:MM:ss");

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame)
            throws Exception {

        System.out.println("服务端收到消息：" + textWebSocketFrame.text());
        // 回复浏览器

        String resp = sdf.format(new Date()) + ": " + textWebSocketFrame.text();
        // 转发给所有的客户端
//        ChannelSupervise.send2All(new TextWebSocketFrame(resp));
        // 发送给当前客户单
        // channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(resp));
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 添加连接
        System.out.println("客户端加入连接：" + ctx.channel());
        ctx.channel().remoteAddress();
//        ChannelSupervise.addChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 断开连接
        System.out.println("客户端断开连接：" + ctx.channel());
//        ChannelSupervise.removeChannel(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生：" + cause.getMessage());
        ctx.channel().close();
    }
}